package UIUtils {
	import UIFree.CLoader;
	
	import com.adobe.images.JPGEncoder;
	
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.utils.ByteArray;
	
	public class uif_frameData extends Object {
		private var _data		: Array;
		
		private const SIGNATURE		: String = 'VFD.V01';
		private const FORMATERROR 	: String = 'Неверный формат данных';
		
		public function uif_frameData() {
			super();
			_data = new Array();
		}
		
		public function addData(dataName: String, a_data : ByteArray): void {
			_data.push({
				name: dataName,
				data: a_data
			});
		}
		
		public function getByName(a_name: String): ByteArray {
			var filter: Array = _data.filter(function(item: Object, index: int, arr: Array): Boolean {
				return item.name == a_name;
			});
			return (filter.length>0)?filter[0].data:null;
		}
		
		public function nameAsLoader(a_name: String, onComplete: Function): Boolean {
			var ba: ByteArray = getByName(a_name);
			if (ba) {
				var loader: CLoader = new CLoader(null, '', function(e: Event): void {
					onComplete(loader);
				});
				loader.loadBytes(ba);
				return true;
			} else return false;
		}
		
		public function nameAsBitmapData(a_name: String, onComplete: Function): Boolean {
			return nameAsLoader(a_name, function(loader: Loader): void {
				var bd: BitmapData = new BitmapData(loader.contentLoaderInfo.width, loader.contentLoaderInfo.height);
				bd.draw(loader);
				loader.unload();
				onComplete(bd);
			});
		}
		
		public function get data(): Array {
			return _data;
		}
		
		public function addObject(dataName: String, a_obj : Object): void {
			var ba: ByteArray = new ByteArray();
			ba.writeObject(a_obj);
			addData(dataName, ba);
		}
		
		public function addBitmapDataJPG(imageName: String, image: BitmapData): void {
			var jpg: JPGEncoder = new JPGEncoder(80);
			addData(imageName, jpg.encode(image));
		}
		
		public function get bytes(): ByteArray {
			var ba: ByteArray = new ByteArray();
			ba.writeUTF(SIGNATURE);
			ba.writeInt(_data.length);
			_data.forEach(function(item: Object, index: int, arr: Array): void {
				ba.writeUTF(item.name);
				ba.writeInt((item.data as ByteArray).length);
				ba.writeBytes(item.data);
			});
			return ba;
		}
		
		public function set bytes(ba: ByteArray): void {
			_data.splice(0, _data.length);
			if (ba.readUTF() == SIGNATURE) {
				var count: int = ba.readInt();
				for (var i: int; i<count; i++) {
					var record: Object = {};
					record.name = ba.readUTF();
					record.data = new ByteArray();
					ba.readBytes(record.data, 0, ba.readInt());
					_data.push(record);
				}
			} else throw new IOError(FORMATERROR);
		}
	}
}